home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7540 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why does this work?
  5. Date: 25 Feb 1996 12:16:00 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4gqg20INN21s@keats.ugrad.cs.ubc.ca>
  8. References: <4g8f7o$adt@ncar.ucar.edu> <4geg2t$k3f@news.cencom.net>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4geg2t$k3f@news.cencom.net>, Bill Wendling <tanp@ns> wrote:
  12.  >Jim Rosinski inexplicably wrote:
  13.  >
  14.  >} Could someone please explain why the following code works?  In particular, I
  15.  >} am perplexed as to why "sub1" and "sub2" declared as elements of "cmndtable"
  16.  >} are valid "pointers to function returning void" (i.e. see the definition of
  17.  >} "cmndstruct").  When executed, the net result is indeed to invoke two
  18.  >} functions, "sub1", and "sub2" (tested on Solaris, AIX, and UNICOS).
  19.  >
  20.  >} #include <stdio.h>
  21.  >} main()
  22.  >} {
  23.  >}   void sub1(), sub2();
  24.  >
  25.  >}   struct cmndstruct {
  26.  >}     void (*funcnam)();
  27.  >}   };
  28.  >
  29.  >}   struct cmndstruct cmndtable[] = {
  30.  >}     sub1,
  31.  >}     sub2,
  32.  >}     NULL
  33.  >}   };
  34.  >/*
  35.  >sub1 and sub2 are the reference to the functions that they call.  This has
  36.  >the same effect of doing:
  37.  >
  38.  >void sub1();
  39.  >void (*funcnam)();
  40.  >
  41.  >funcnam = sub1;
  42.  >
  43.  >This is exactly how you assign a function to a function pointer.
  44.  
  45. You missed the point. He obviously wanted to know why his functions are being
  46. called, depite that he has omitted parentheses from the aggregate initializers,
  47. which place the sub1, and sub2 above on the same nesting level as structure
  48. initializers. It appears as though sub1 and sub2 can be directly (and
  49. incorrectly) assigned as members of a array of structures.
  50.  
  51. This is a feature of ANSI C. In aggregate initializers, braces may be elided,
  52. in which case the initializer elements are handed to whatever fields are
  53. available in the aggregate variable in sequence. Thus, you can do:
  54.  
  55.     int myarray[3][3][3] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  56.  
  57. Instead of several levels of bracket nesting.
  58.  
  59. -- 
  60.  
  61.